﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace WW.NActiveRecord.Tests{
    /// <summary>
    /// 对程序多次运行进行性能测量 TODO  内存测量 System.Diagnostics
    /// </summary>
    public class Scale
    {
        private String message;
        private long count;
        private TimeSpan time;

        private Scale(String message, long count, TimeSpan time)
        {
            this.message = message;
            this.count = count;
            this.time = time;
        }

        /// <summary>
        /// 按要求的测试次数(count)运行action,并给出测试性能结果
        /// </summary>
        /// <param name="message">提示消息</param>
        /// <param name="count">运行次数</param>
        /// <param name="action">要多次运行的代码块</param>
        /// <returns>Test结果</returns>
        public static Scale Run(String message, long count, Action action)
        {
            DateTime start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                action();
            }
            DateTime end = DateTime.Now;
            return new Scale(message, count, end - start);
        }

        /// <summary>
        /// 提示消息
        /// </summary>
        public String Message
        {
            get { return message; }
        }


        /// <summary>
        /// 运行次数
        /// </summary>
        public long Count
        {
            get { return count; }
        }


        /// <summary>
        /// 总耗时
        /// </summary>
        public TimeSpan Time
        {
            get { return time; }
        }

        /// <summary>
        /// 每次运行的平均时间(毫秒)
        /// </summary>
        public double AvgMilliseconds
        {
            get { return Time.Ticks / 10000.0 / count; }
        }

        /// <summary>
        /// 把测试结果打印到控制台
        /// </summary>
        public void PrintResult()
        {
            Debug.WriteLine(ToString());
        }

        public override string ToString(){
            return string.Format("\n{0}:运行{1}次({2}ms,{3}ms/次)", message, count, Time.TotalMilliseconds, AvgMilliseconds);
        }
    }
}